package com.kanq.service.impl;

import com.kanq.enums.ChatModeType;
import com.kanq.handler.*;
import com.kanq.pojo.context.ChatContext;
import com.kanq.pojo.request.ChatRequest;
import com.kanq.service.*;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;


/**
 * @author ageer
 */
@Service
@Slf4j
public class SiliconFlowServiceImpl implements IChatService {

    @Value("${chunk.top-k}")
    private int topK;

    @Value("${rerank.context-max-length}")
    private int contextMaxLength;

    @Value("${rerank.score-threshold}")
    private double scoreThreshold;
    @Value("${rerank.model}")
    private String rerankModelName;
    @Value(value = "${rerank.host}")
    private String rerankHost;
    @Value("${rerank.key}")
    private String rerankKey;

    @Resource
    private QdrantService qdrantService;

    @Resource
    private KanqAiPromptService kanqAiPromptService;

    @Resource
    private KanqAiFileChunkService kanqAiFileChunkService;

    @Resource
    private KanqAiFileService kanqAiFileService;

    @Resource
    private KanqAiHistoryService kanqAiHistoryService;

    @Resource
    private KanqAiHistoryQuestionService kanqAiHistoryQuestionService;

    @Resource
    private KanqAiHistoryAnswerService kanqAiHistoryAnswerService;

    @Resource
    private ChatClient defaultClient;

    @Override
    public SseEmitter chat(ChatRequest chatRequest, SseEmitter emitter, ConcurrentHashMap<String, SseEmitter> taskEmitterMap) {
        // 初始化责任链处理器
        ChatHandlerChain handlerChain = new ChatHandlerChain(
                new TemplateHandler(kanqAiPromptService),
                new KeywordSearchHandler(kanqAiFileChunkService),
                new VectorSearchHandler(qdrantService, topK),
                new FileRetrievalHandler(kanqAiFileService),
                new ResponseGeneratorHandler(chatRequest, defaultClient,
                        kanqAiHistoryService,
                        kanqAiHistoryQuestionService,
                        kanqAiHistoryAnswerService,
                        contextMaxLength,
                        scoreThreshold,
                        rerankModelName,
                        rerankHost,
                        rerankKey)
        );

        // 创建SSE响应
        emitter = new SseEmitter(3 * 60 * 1000L);
        String taskId = UUID.randomUUID().toString();
        taskEmitterMap.put(taskId, emitter);

        // 异步处理请求
        SseEmitter finalEmitter = emitter;
        Executors.newSingleThreadExecutor().submit(() -> {
            ChatContext context = new ChatContext(chatRequest, finalEmitter, taskId);
            handlerChain.handle(context);
        });

        return emitter;
    }

    @Override
    public String getCategory() {
        return ChatModeType.CHAT.getCode();
    }

}
